package com.nchu.commondevelopmentframework.controller;

import com.nchu.commondevelopmentframework.common.constant.ApiCodeConstant;
import com.nchu.commondevelopmentframework.common.domain.ApiResult;
import com.nchu.commondevelopmentframework.common.utils.JwtUtils;
import com.nchu.commondevelopmentframework.common.utils.RedisUtil;
import com.nchu.commondevelopmentframework.converter.UserConverter;
import com.nchu.commondevelopmentframework.dto.LoginUserDTO;
import com.nchu.commondevelopmentframework.dto.UserDTO;
import com.nchu.commondevelopmentframework.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * @className: LoginController
 * @description: 登录控制类
 * @author: Li Chuanwei
 * @date: 2024/02/06 23:43
 * @Company: Copyright [日期] by [作者或个人]
 **/

@RestController
public class LoginController {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private JwtUtils jwtUtils;

    @PostMapping("/user/login")
    public ApiResult<UserVO> login(@RequestBody @Validated UserDTO userDTO, @RequestHeader(value = "Client-Type",required = false,defaultValue = "") String clientType){
        try {
            UsernamePasswordAuthenticationToken authenticationToken
                    = new UsernamePasswordAuthenticationToken(userDTO.getUserName(),userDTO.getPassword());
            Authentication authenticate = authenticationManager.authenticate(authenticationToken);
            SecurityContextHolder.getContext().setAuthentication(authenticate);
            LoginUserDTO userDetails = (LoginUserDTO) authenticate.getPrincipal();

            //获取用户权限信息
            List<String> authorityString = new ArrayList<>();

            Collection<? extends GrantedAuthority> authorities = userDetails.getAuthorities();
            for (GrantedAuthority authority : authorities) {
                authorityString.add(authority.getAuthority());
            }

            //用户身份验证成功，生成并返回jwt令牌
            Map<String, Object> claims = new HashMap<>();
            claims.put("username", userDetails.getUsername());
            claims.put("authorityString", authorityString);
            claims.put("clientType", clientType);
            String jwtToken = jwtUtils.sign(String.valueOf(userDetails.getId()),claims);
            Map<String, Object> map = new HashMap<>();
            map.put(clientType, claims);
            redisUtil.hmset("login:" + userDetails.getId(), map);

            UserVO userVO = UserConverter.INSTANCE.loginUserDTOToUserVO(userDetails);
            userVO.setToken(jwtToken);
            return ApiResult.success(userVO);
        }
        catch (Exception ex) {
            //用户身份验证失败，返回登陆失败提示
            return ApiResult.fail(ApiCodeConstant.LOGIN_FAILED,"用户名或密码错误！");
        }
    }

    @PostMapping("/user/login1")
    public ApiResult<String> login1(){
        return ApiResult.success("登录成功");
    }
}
